﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Connector;
using System.Diagnostics;
namespace Gobang
{
    public class Client
    {
        public ConnectorClient m_client;
        public Action<object[]> m_requestHandler;
        public Client()
        {
            m_client = new ConnectorClient();
            m_client.m_ReceiveMsgHandler += HandleMsg;
        }
        public bool Connect(string ip, int port)
        {
            bool result = m_client.Connect(ip, port);
            return result;
        }
        public void Close()
        {
            m_client.Close();
        }
        public void SignIn(string name)
        {
            SendParams("SIGN_IN", name);
        }

        private void HandleMsg(byte[] data)
        {
            object[] args = ConnectorProto.Decode(data);
            m_requestHandler.Invoke(args);
        }

        public void SendParams(params object[] args)
        {
            if (!m_client.IsConnected())
                return;
            if (args[0].GetType() != typeof(string))
            {
                Debug.WriteLine("Client::SendParams First parameter should be string!");
                return;
            }
            byte[] data = ConnectorProto.Encode(args);
            m_client.SendData(data);
        }
    }
}
